﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SQLite;
using seo_tool.lib;

namespace seo_tool
{
    public partial class FormMain : Form
    {
        Thread thread;
        Thread thread_xg;
        Sqlite conn;
        public FormMain()
        {
            InitializeComponent();

            CheckForIllegalCrossThreadCalls = false;
            conn = new Sqlite("datainfo.db");

            GetSearch();
            GetShouluList();

            GetSearch_xg();
            GetXiangguanList();
        }

        private void ButtonFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog {
                Multiselect = false,//该值确定是否可以选择多个文件
                Title = "请选择文件夹",
                Filter = "所有文件(*.*)|*.*",
            };
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string file = dialog.FileName;
                textBoxFile.Text = file;
            }
        }

        private void ButtonImport_Click(object sender, EventArgs e)
        {
            if (textBoxFile.Text == "")
            {
                MessageBox.Show("请选择excel文件");
                return;
            }
            if (MessageBox.Show("确认导入？", "清空当前数据并导入", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }
            dataGridViewData.Rows.Clear();
            conn.clear("shoulu");
            List<string> urls = Excel.Read(textBoxFile.Text);
            foreach (string url in urls)
            {
                conn.insert($"insert into shoulu (url) values ('{url}')");
            }
            GetShouluList();
        }

        private void ButtonStart_Click(object sender, EventArgs e)
        {
            if (dataGridViewData.Rows.Count == 0)
            {
                MessageBox.Show("url列表为空");
                return;
            }
            if (buttonStart.Text == "停止")
            {
                thread.Abort();
                while (true)
                {
                    Thread.Sleep(500);
                    if (!thread.IsAlive)
                    {
                        thread = null;
                        SetButtonEnd(buttonStart);
                        richTextBoxInfo.Text += "停止执行\r\n";
                        richTextBoxInfo.SelectionStart = richTextBoxInfo.Text.Length;
                        richTextBoxInfo.ScrollToCaret();
                        richTextBoxInfo.Refresh();
                        break;
                    }
                }
            }
            else
            {
                if (MessageBox.Show("确认执行？", "执行", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }

                string search = SetSearch();
                conn.resetShoulu();
                GetShouluList();
                richTextBoxInfo.Clear();

                richTextBoxInfo.Text += "开始执行，获取收录，请等待...\r\n";
                richTextBoxInfo.SelectionStart = richTextBoxInfo.Text.Length;
                richTextBoxInfo.ScrollToCaret();
                richTextBoxInfo.Refresh();

                SetButtonStart(buttonStart);
                if (thread != null)
                {
                    thread.Abort();
                    thread = null;
                }
                thread = new Thread(new ThreadStart(() => {
                    Shoulu shoulu = new Shoulu(search, conn, dataGridViewData, richTextBoxInfo);
                    shoulu.Run();
                    SetButtonEnd(buttonStart);
                    richTextBoxInfo.Text += "执行完毕\r\n";
                    richTextBoxInfo.SelectionStart = richTextBoxInfo.Text.Length;
                    richTextBoxInfo.ScrollToCaret();
                    richTextBoxInfo.Refresh();
                    thread.Abort();
                }));
                thread.IsBackground = true;
                thread.Start();
            }
        }

        private void ButtonClear_Click(object sender, EventArgs e)
        {
            conn.clear("shoulu");
            dataGridViewData.Rows.Clear();
        }

        private void ButtonExport_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveDlg = new SaveFileDialog();
            saveDlg.Filter = "文本文件|*.xlsx";
            if (saveDlg.ShowDialog() == DialogResult.OK)
            {
                SQLiteDataReader reader = conn.select("shoulu");
                string msg = Excel.Write(saveDlg.FileName, reader);
                MessageBox.Show(msg);
            }
        }

        private void SetButtonStart(Button button)
        {
            if (button.Name == "buttonStart")
            {
                foreach (Control ctl in tabPageShoulu.Controls)
                {
                    if (ctl is Button)
                    {
                        Button btn = ctl as Button;
                        btn.Enabled = false;
                    }
                }
            }
            else
            {
                foreach (Control ctl in tabPageXiangguan.Controls)
                {
                    if (ctl is Button)
                    {
                        Button btn = ctl as Button;
                        btn.Enabled = false;
                    }
                }
            }
            
            button.Text = "停止";
            button.Enabled = true;
        }

        private void SetButtonEnd(Button button)
        {
            if (button.Name == "buttonStart")
            {
                foreach (Control ctl in tabPageShoulu.Controls)
                {
                    if (ctl is Button)
                    {
                        Button btn = ctl as Button;
                        btn.Enabled = true;
                    }
                }
            }
            else
            {
                foreach (Control ctl in tabPageXiangguan.Controls)
                {
                    if (ctl is Button)
                    {
                        Button btn = ctl as Button;
                        btn.Enabled = true;
                    }
                }
            }
            
            button.Text = "开始";
        }

        private void HelpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormHelp form = new FormHelp();
            form.ShowDialog();
        }

        private void GetShouluList()
        {
            dataGridViewData.Rows.Clear();
            SQLiteDataReader reader = conn.select("shoulu");
            while (reader.Read())
            {
                int index = dataGridViewData.Rows.Add();
                dataGridViewData.Rows[index].Cells["is_run"].Value = reader["is_run"];
                dataGridViewData.Rows[index].Cells["url"].Value = reader["url"];
                dataGridViewData.Rows[index].Cells["title"].Value = reader["title"];
                dataGridViewData.Rows[index].Cells["is_shoulu"].Value = reader["is_shoulu"];
                dataGridViewData.Rows[index].Cells["suoyin"].Value = reader["suoyin"];
                dataGridViewData.Rows[index].Cells["search"].Value = reader["search"];
            }
        }

        private void GetSearch()
        {
            string value = conn.findConfig("search");
            if (value == "百度PC")
            {
                radioButtonBaidu.Checked = true;
                radioButtonSougou.Checked = false;
                radioButtonBaiduM.Checked = false;
                radioButtonSougouM.Checked = false;
                radioButtonShenmaM.Checked = false;
            }
            else if (value == "搜狗PC")
            {
                radioButtonBaidu.Checked = false;
                radioButtonSougou.Checked = true;
                radioButtonBaiduM.Checked = false;
                radioButtonSougouM.Checked = false;
                radioButtonShenmaM.Checked = false;
            }
            else if (value == "百度M")
            {
                radioButtonBaidu.Checked = false;
                radioButtonSougou.Checked = false;
                radioButtonBaiduM.Checked = true;
                radioButtonSougouM.Checked = false;
                radioButtonShenmaM.Checked = false;
            }
            else if (value == "搜狗M")
            {
                radioButtonBaidu.Checked = false;
                radioButtonSougou.Checked = false;
                radioButtonBaiduM.Checked = false;
                radioButtonSougouM.Checked = true;
                radioButtonShenmaM.Checked = false;
            }
            else if (value == "神马M")
            {
                radioButtonBaidu.Checked = false;
                radioButtonSougou.Checked = false;
                radioButtonBaiduM.Checked = false;
                radioButtonSougouM.Checked = false;
                radioButtonShenmaM.Checked = true;
            }
        }

        private string SetSearch()
        {
            string value = "";
            if (radioButtonBaidu.Checked)
            {
                value = "百度PC";
            }
            else if (radioButtonSougou.Checked)
            {
                value = "搜狗PC";
            }
            else if (radioButtonBaiduM.Checked)
            {
                value = "百度M";
            }
            else if (radioButtonSougouM.Checked)
            {
                value = "搜狗M";
            }
            else if (radioButtonShenmaM.Checked)
            {
                value = "神马M";
            }
            conn.update($"UPDATE config SET value = '{value}' WHERE key = 'search'");
            return value;
        }

        //--------------------------------------------------------------------

        private void buttonFile_xg_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog
            {
                Multiselect = false,//该值确定是否可以选择多个文件
                Title = "请选择文件夹",
                Filter = "所有文件(*.*)|*.*",
            };
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string file = dialog.FileName;
                textBoxFile_xg.Text = file;
            }
        }

        private void buttonImport_xg_Click(object sender, EventArgs e)
        {
            if (textBoxFile_xg.Text == "")
            {
                MessageBox.Show("请选择excel文件");
                return;
            }
            if (MessageBox.Show("确认导入？", "清空当前数据并导入", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }
            dataGridViewData_xg.Rows.Clear();
            conn.clear("xiangguan");
            List<string> keywords = Excel.Read(textBoxFile_xg.Text);
            foreach (string keyword in keywords)
            {
                conn.insert($"insert into xiangguan (keyword) values ('{keyword}')");
            }
            GetXiangguanList();
        }

        private void buttonStart_xg_Click(object sender, EventArgs e)
        {
            if (dataGridViewData_xg.Rows.Count == 0)
            {
                MessageBox.Show("url列表为空");
                return;
            }
            if (buttonStart_xg.Text == "停止")
            {
                thread_xg.Abort();
                while (true)
                {
                    Thread.Sleep(500);
                    if (!thread_xg.IsAlive)
                    {
                        thread_xg = null;
                        SetButtonEnd(buttonStart_xg);
                        richTextBoxInfo_xg.Text += "停止执行\r\n";
                        richTextBoxInfo_xg.SelectionStart = richTextBoxInfo_xg.Text.Length;
                        richTextBoxInfo_xg.ScrollToCaret();
                        richTextBoxInfo_xg.Refresh();
                        break;
                    }
                }
            }
            else
            {
                if (MessageBox.Show("确认执行？", "执行", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }

                string search_xg = SetSearch_xg();
                conn.resetXiangguan();
                GetXiangguanList();
                richTextBoxInfo_xg.Clear();

                richTextBoxInfo_xg.Text += "开始执行，获取相关词，请等待...\r\n";
                richTextBoxInfo_xg.SelectionStart = richTextBoxInfo_xg.Text.Length;
                richTextBoxInfo_xg.ScrollToCaret();
                richTextBoxInfo_xg.Refresh();

                SetButtonStart(buttonStart_xg);
                if (thread_xg != null)
                {
                    thread_xg.Abort();
                    thread_xg = null;
                }
                thread_xg = new Thread(new ThreadStart(() => {
                    Xiangguan xiangguan = new Xiangguan(search_xg, conn, dataGridViewData_xg, richTextBoxInfo_xg);
                    xiangguan.Run((int)numericUpDownLevel.Value);
                    SetButtonEnd(buttonStart_xg);
                    richTextBoxInfo_xg.Text += "执行完毕\r\n";
                    richTextBoxInfo_xg.SelectionStart = richTextBoxInfo_xg.Text.Length;
                    richTextBoxInfo_xg.ScrollToCaret();
                    richTextBoxInfo_xg.Refresh();
                    thread_xg.Abort();
                }));
                thread_xg.IsBackground = true;
                thread_xg.Start();
            }
        }

        private void buttonClear_xg_Click(object sender, EventArgs e)
        {
            conn.clear("xiangguan");
            dataGridViewData_xg.Rows.Clear();
        }

        private void buttonExport_xg_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveDlg = new SaveFileDialog();
            saveDlg.Filter = "文本文件|*.xlsx";
            if (saveDlg.ShowDialog() == DialogResult.OK)
            {
                SQLiteDataReader reader = conn.select("xiangguan");
                string msg = Excel.Write_xg(saveDlg.FileName, reader);
                MessageBox.Show(msg);
            }
        }

        private void GetXiangguanList()
        {
            dataGridViewData_xg.Rows.Clear();
            SQLiteDataReader reader = conn.select("xiangguan");
            while (reader.Read())
            {
                int index = dataGridViewData_xg.Rows.Add();
                dataGridViewData_xg.Rows[index].Cells["id"].Value = reader["id"];
                dataGridViewData_xg.Rows[index].Cells["keyword"].Value = reader["keyword"];
                dataGridViewData_xg.Rows[index].Cells["pid"].Value = reader["pid"];
                dataGridViewData_xg.Rows[index].Cells["level"].Value = reader["level"];
                dataGridViewData_xg.Rows[index].Cells["xiala"].Value = reader["xiala"];
                dataGridViewData_xg.Rows[index].Cells["xiangguan"].Value = reader["xiangguan"];
                dataGridViewData_xg.Rows[index].Cells["is_run_xg"].Value = reader["is_run"];
                dataGridViewData_xg.Rows[index].Cells["search_xg"].Value = reader["search"];
            }
            reader.Close();
        }

        private void GetSearch_xg()
        {
            string value = conn.findConfig("search_xg");
            if (value == "百度PC")
            {
                radioButtonBaidu_xg.Checked = true;
                radioButtonSougou_xg.Checked = false;
                radioButtonBaiduM_xg.Checked = false;
                radioButtonSougouM_xg.Checked = false;
                radioButtonShenmaM_xg.Checked = false;
            }
            else if (value == "搜狗PC")
            {
                radioButtonBaidu_xg.Checked = false;
                radioButtonSougou_xg.Checked = true;
                radioButtonBaiduM_xg.Checked = false;
                radioButtonSougouM_xg.Checked = false;
                radioButtonShenmaM_xg.Checked = false;
            }
            else if (value == "百度M")
            {
                radioButtonBaidu_xg.Checked = false;
                radioButtonSougou_xg.Checked = false;
                radioButtonBaiduM_xg.Checked = true;
                radioButtonSougouM_xg.Checked = false;
                radioButtonShenmaM_xg.Checked = false;
            }
            else if (value == "搜狗M")
            {
                radioButtonBaidu_xg.Checked = false;
                radioButtonSougou_xg.Checked = false;
                radioButtonBaiduM_xg.Checked = false;
                radioButtonSougouM_xg.Checked = true;
                radioButtonShenmaM_xg.Checked = false;
            }
            else if (value == "神马M")
            {
                radioButtonBaidu_xg.Checked = false;
                radioButtonSougou_xg.Checked = false;
                radioButtonBaiduM_xg.Checked = false;
                radioButtonSougouM_xg.Checked = false;
                radioButtonShenmaM_xg.Checked = true;
            }
        }

        private string SetSearch_xg()
        {
            string value = "";
            if (radioButtonBaidu_xg.Checked)
            {
                value = "百度PC";
            }
            else if (radioButtonSougou_xg.Checked)
            {
                value = "搜狗PC";
            }
            else if (radioButtonBaiduM_xg.Checked)
            {
                value = "百度M";
            }
            else if (radioButtonSougouM_xg.Checked)
            {
                value = "搜狗M";
            }
            else if (radioButtonShenmaM_xg.Checked)
            {
                value = "神马M";
            }
            conn.update($"UPDATE config SET value = '{value}' WHERE key = 'search_xg'");
            return value;
        }

        
    }
}
